from itsdangerous import TimedJSONWebSignatureSerializer as TJSWS
from django.conf import settings

# 加密 openid
def generate_sign_openid(openid):
    # 创建TJSWS对象      使用django的settings配置的秘钥          设置有效期
    serializer = TJSWS(secret_key=settings.SECRET_KEY, expires_in=300)
    # 加密数据  # 使用dumps方法进行加密
    sign_openid = serializer.dumps({"openid": openid})

    # 返回数据
    return sign_openid.decode()

# 解密openid
def decode_sign_openid(sign_openid):
    # 创建TJSWS对象
    serializer = TJSWS(secret_key=settings.SECRET_KEY, expires_in=300)
    # 解密数据
    try:   # 防止有效期过期报错
        dict_data = serializer.loads(sign_openid)  # 使用loads方法解密
    except Exception as e:
        return None
    # 返回openid
    return dict_data.get("openid")

